package com.blank.shop.security.filter;

import com.blank.shop.security.controller.ValidateCodeController;
import com.blank.shop.security.handler.MyAuthenticationFailureHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.Objects;

/**
 * <br/>Date 2021/9/10
 * <br/>Time 11:11:36
 *
 * @author _blank
 */
@Slf4j
public class SmsValidateCodeFilter extends ImageValidateCodeFilter {

    /**
     * 处理登录请求
     */
    public static final String LOGIN_PROCESSING_URL = "/authentication/sms.html";

    public SmsValidateCodeFilter(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
        super(myAuthenticationFailureHandler);
        this.setFilterUrl(LOGIN_PROCESSING_URL);
    }

    @Override
    protected void validate(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
        // session 验证码
        final String sessionCaptchaCode = (String) servletWebRequest.getAttribute(ValidateCodeController.SESSION_CAPTCHA_KEY, RequestAttributes.SCOPE_SESSION);
        // 前端用户验证码
        final String requestVerificationCode = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsVerificationCode");

        if (StringUtils.isBlank(requestVerificationCode)) {
            throw new ValidateCodeException("验证码的值不能为空！");
        }
        if (Objects.isNull(sessionCaptchaCode)) {
            throw new ValidateCodeException("验证码不存在！");
        }
        // fixme 需要判断验证码是否超时逻辑
        if (!StringUtils.equalsIgnoreCase(sessionCaptchaCode, requestVerificationCode)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        servletWebRequest.removeAttribute(ValidateCodeController.SESSION_CAPTCHA_KEY, RequestAttributes.SCOPE_SESSION);
    }

}
